package com.spark.common.helper

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.support.design.widget.BottomSheetDialog
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v4.content.FileProvider
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.spark.colliery.common.ext.gone
import com.spark.common.R
import com.spark.common.ext.isAlive
import com.spark.common.ext.permissionSettings
import com.spark.common.ext.uriPath
import com.spark.common.widget.Alert
import org.jetbrains.anko.*
import org.jetbrains.anko.recyclerview.v7.recyclerView
import java.io.File
import java.text.SimpleDateFormat
import java.util.*

/**
 * 选择照片、图片
 *
 * @param authority FileProvider 的授权路径
 */
class Picker(var activity: Activity, items: Array<String> = arrayOf("拍照", "相册"), private var authority: String = "com.spark.colliery.fileprovider") {
    private val IMG_TYPE = "image/*"
    private val sdf = SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.getDefault())
    private var bottomSheet = BottomSheetDialog(activity)
    private val rootView: View = LayoutInflater.from(activity).inflate(R.layout.layout_photo_popup, null)
    private var recyCategory: RecyclerView
    private var tvCancel: TextView
    private var categoryAdapter: CategoryAdapter

    init {
        recyCategory = rootView.findViewById(R.id.recy_bottom_category)
        tvCancel = rootView.findViewById(R.id.tv_bottom_cancel)

        categoryAdapter = CategoryAdapter(R.layout.item_picker).apply {
            addData(items.toMutableList())
            setOnItemClickListener { adapter, view, position ->
                if (bottomSheet.isShowing) bottomSheet.dismiss()
                when (position) {
                    0 -> {
                        gotoCamera()
                    }
                    1 -> {
                        gotoGallery()
                    }
                }
            }
        }
        recyCategory.apply {
            adapter = categoryAdapter
            layoutManager = LinearLayoutManager(activity)
        }
        tvCancel.setOnClickListener { if (bottomSheet.isShowing) bottomSheet.dismiss() }
        bottomSheet.apply {
            setCancelable(true)
            setCanceledOnTouchOutside(true)
            setContentView(rootView)
        }
    }

    companion object {
        private val REQ_GALLERY = 0x6666
        private val PERM_GALLERY = 0x7777
        private val REQ_CAMERA = 0x8888
        private val PERM_CAMERA = 0x9999

        private var photoPath: String = ""
        private val listeners = mutableListOf<OnImagePickedListener>()
        private var callback: OnImagePickedListener? = null

        /**
         * OnActivityResulted
         */
        fun onActivityResulted(activity: Activity, requestCode: Int, resultCode: Int, data: Intent?) {
            if (!activity.isAlive()) {
                Log.e("Picker", "activity 已被销毁了")
                return
            }
            when (requestCode) {
                REQ_CAMERA -> if (resultCode != Activity.RESULT_OK) {
                    photoPath = ""
                }
                REQ_GALLERY -> photoPath = if (resultCode == Activity.RESULT_OK) {
                    val uri = data?.data
                    activity.uriPath(uri)
                } else {
                    ""
                }
            }
            /*listeners.forEach {
                it.onPicked(photoPath)
            }*/
            callback?.onPicked(photoPath)
            photoPath = ""
        }

        /**
         * 添加图片选择监听
         */
        fun addImagePickedListener(listener: (String) -> Unit) {
            listeners.add(object : OnImagePickedListener {
                override fun onPicked(path: String) {
                    listener(path)
                }
            })
        }
    }

    fun show() {
        bottomSheet.show()
    }

    /**
     * @param
     */
    fun show(listener: (String) -> Unit) {
        show()
        //addImagePickedListener(listener)
        callback = object : OnImagePickedListener {
            override fun onPicked(path: String) {
                listener(path)
            }

        }
    }


    /**
     * 前往相机📷
     */
    private fun gotoCamera() {
        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED &&
                ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA), PERM_CAMERA)
        } else {
            val file = cacheImageFile(sdf.format(System.currentTimeMillis()))
            photoPath = file.absolutePath

            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file))
                activity.startActivityForResult(intent, REQ_CAMERA)
            } else {
                try {
                    val intent = Intent()
                    val uri = FileProvider.getUriForFile(activity, authority, file)
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                    intent.action = MediaStore.ACTION_IMAGE_CAPTURE
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri)
                    activity.startActivityForResult(intent, REQ_CAMERA)
                } catch (e: Exception) {
                    e.printStackTrace()
                    Alert.Builder(activity, "是否同意前往设置页面授予权限")
                            .affirm("是") { d, _ ->
                                d.dismiss()
                                activity.permissionSettings()
                            }
                            .cancel("否") { d, _ ->
                                d.dismiss()
                            }
                            .create()
                            .show()
                }
            }
        }
    }

    /**
     * 前往相册🐘
     */
    private fun gotoGallery() {
        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), PERM_GALLERY)
        } else {
            val intent = Intent()
            intent.type = IMG_TYPE
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            intent.action = Intent.ACTION_GET_CONTENT
            activity.startActivityForResult(intent, REQ_GALLERY)
        }
    }

    private fun cacheImageFile(name: String): File {
        return if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
            File(activity.externalCacheDir, "$name.jpeg")
        } else {
            File(activity.cacheDir, "$name.jpeg")
        }
    }

    /**
     * Adapter
     */
    inner class CategoryAdapter(layoutRes: Int) : BaseQuickAdapter<String, BaseViewHolder>(layoutRes) {
        override fun convert(helper: BaseViewHolder?, item: String?) {
            if (item == null) return
            helper?.apply {
                setText(R.id.tv_item, item)
                getView<View>(R.id.divider).apply {
                    gone(adapterPosition >= data.size - 1)
                }
            }
        }

    }

    interface OnImagePickedListener {
        fun onPicked(path: String)
    }
}

/**
 * @test [ankoStyle]
 */
class PickerUI : AnkoComponent<Activity> {
    override fun createView(ui: AnkoContext<Activity>) = with(ui) {
        verticalLayout {
            lparams(matchParent, matchParent)
            gravity = bottom

            val recyItems = recyclerView().lparams(matchParent, wrapContent) {
                backgroundResource = R.drawable.bg_round10_rect_white
            }

            val tvCancel = themedTextView(R.style.SelectBackgroundStyle) {
                textColor = resources.getColor(R.color.color0092dfblue)
                textSize = sp(17).toFloat()
                gravity = Gravity.CENTER
                text = "取消"
                topPadding = dip(14)
                bottomPadding = dip(14)
            }.lparams(matchParent, wrapContent) {
                topMargin = dip(16)
            }
        }
    }

}